package com.iwords.android;

import android.media.MediaPlayer;

public class IWordsMediaPlayer {
	private static IWordsMediaPlayer INSTANCE;
	MediaPlayer mediaPlayer;
	private IWordsMediaPlayer(){
		this.mediaPlayer = new MediaPlayer();
		MediaPlayerListener listener = new MediaPlayerListener();
		mediaPlayer.setOnCompletionListener(listener);
		mediaPlayer.setOnErrorListener(listener);
	}
	public static IWordsMediaPlayer getInstance(){
		if(INSTANCE == null) {
			INSTANCE = new IWordsMediaPlayer();
		}
		return INSTANCE;
	}
	public void play(String url){
		//System.out.println("MediaPlayerManager.play("+url+")");
		try{
			if(mediaPlayer.isPlaying()) return;
		}catch(Exception e){
			e.printStackTrace();
		}
		try{
			mediaPlayer.setDataSource(url);
			mediaPlayer.prepare();
			mediaPlayer.start();
		}catch(Exception e){
			mediaPlayer.reset();
			//e.printStackTrace();
		}

	}
	public MediaPlayer getMediaPlayer(){
		return this.mediaPlayer;
	}
	/** 延迟三秒读单词 */
	public void read(WordStatus word, String voiceHref) {
		//System.out.println("ShowWordCountdown.loadVoice()");
		String spelling = word.getSpelling();
		String href = voiceHref;
		//System.out.println("ShowWordCountdown.loadVoice() href=" + href);
		href += spelling.substring(0,1).toLowerCase() + "/" + CodeUtils.encode(spelling) +".wav";
		//System.out.println("ShowWordCountdown.loadVoice() href=" + href);
		IWordsMediaPlayer.getInstance().play(href);
	}

	class MediaPlayerListener implements MediaPlayer.OnCompletionListener,MediaPlayer.OnErrorListener{
		public void onCompletion(MediaPlayer mp){
			//mp.release();
			mp.reset();
		}
		public boolean onError(MediaPlayer mp, int what, int extra){
			try{
				//System.out.println("MediaPlayerListener.onError() media player is going to reset().");
				mp.reset();
				//System.out.println("MediaPlayerListener.onError() media player finished reset().");
				return true;
			}catch(Exception e){
				//System.out.println("MediaPlayerListener.onError() Exception:"+e.getMessage());
			}
			return false;
		}
	}
}
